package com.play.ballen.home.ui

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Build
import android.util.Log
import com.hjq.toast.ToastUtils
import com.play.ballen.R
import com.play.ballen.config.KVConst
import com.play.ballen.databinding.ActivityUserInformationAddBinding
import com.play.ballen.home.vm.PLPFragmentVM
import com.qiniu.android.storage.Configuration
import com.qiniu.android.storage.GlobalConfiguration
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UploadManager
import com.qiniu.android.storage.UploadOptions
import com.yuven.appframework.manager.AppActivitysManager
import com.yuven.appframework.util.MMKVUtil
import com.yuven.appframework.util.imageloader.ImageUtil
import com.yuven.appframework.util.setOnSingleClickListener
import com.yuven.baselib.component.BaseMVVMActivity
import com.yxp.permission.util.lib.PermissionUtil
import com.yxp.permission.util.lib.callback.PermissionResultCallBack
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.filter.Filter
import com.zhihu.matisse.internal.entity.CaptureStrategy
import com.zhihu.matisse.listener.OnCheckedListener
import com.zhihu.matisse.listener.OnSelectedListener
import java.io.File


class AddInformationActivity : BaseMVVMActivity<PLPFragmentVM, ActivityUserInformationAddBinding>() {

    val REQUEST_CODE_CHOOSE = 10020
    val PERMISSION_REQUEST_CODE = 1000
    private var uploadManager: UploadManager? = null
    private val token: String? = null
    private var keyname: String? = null
    var data1: String? = null
    var data2: String? = null
    companion object {
        @JvmStatic
//        fun start(context: Context, data1: String, data2: String) {
//            val starter = Intent(context, AddInformationActivity::class.java)
//            starter.putExtra("key_data1", data1)
//            starter.putExtra("key_data2", data2)
//            context.startActivity(starter)
//        }
        fun start(context: Context) {
            val starter = Intent(context, AddInformationActivity::class.java)
            context.startActivity(starter)
        }
    }



    override fun layoutId(): Int {
        return R.layout.activity_user_information_add

    }

    override fun viewModelClass(): Class<PLPFragmentVM> {
        return PLPFragmentVM::class.java
    }

    override fun initObserver() {
        super.initObserver()
        viewModel.actionAddNameSuccess.observe(this) {
            var photo = MMKVUtil.decodeString(KVConst.PHOTO,false)?:""
            var name = MMKVUtil.decodeString(KVConst.NICK_NAME,false)?:""

            Log.d("xyp","photo.toString()"+photo.toString())
            Log.d("xyp","name.toString()"+name.toString())
            if(photo.isNotEmpty()&&name.isNotEmpty()){
                MainActivity.start(this)
                finish()
            }
            else if(photo.isEmpty()) {
                ToastUtils.show("请上传头像")
            }else if(name.isEmpty()) {
                 ToastUtils.show("请填写昵称")
            }
        }

        viewModel.picToken.observe(this) {
            if(it!=null){
                selectPic()
            }
        }
    }


    override fun initView() {
        dataBinding.layoutTitle.ivBtnBack.setOnClickListener{
            AppActivitysManager.getInstance().finishAllActivity()
            finish()
        }

        dataBinding.flPic.setOnClickListener{
            getPermission()

        }

        dataBinding.btnAdd.setOnSingleClickListener tag@{
            val account = dataBinding.etName.text.toString().trim()
            if (account.isEmpty()) {
                ToastUtils.show("请输入昵称")
                return@tag
            }
            MMKVUtil.encode(KVConst.NICK_NAME, account, false)
            viewModel.addName(account)
        }
    }

    override fun initData() {
        data1 = intent?.getStringExtra("key_data1")
        data2 = intent?.getStringExtra("key_data2")
        if (data1 != null) {
            ImageUtil.instance.loadCircleImage(data1!!, dataBinding.imgAvatar, 0, 0)
        }
        if (data2 != null) {
            dataBinding.etName.setText(data2)
        }
    }

    override fun initIntent(intent: Intent?) {

    }

    private fun selectPic() {
        Matisse.from(this@AddInformationActivity)
            .choose(MimeType.ofImage(), false)
            .countable(true)
            .capture(true)
            .captureStrategy(
                CaptureStrategy(true, "com.play.ballen.fileprovider", "test")
            )
            .maxSelectable(1)
            .addFilter(GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
            .gridExpectedSize(
                resources.getDimensionPixelSize(R.dimen.grid_expected_size)
            )
            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            .thumbnailScale(0.85f)
            .imageEngine(GlideEngine())
            .setOnSelectedListener(OnSelectedListener { uriList: List<Uri?>?, pathList: List<String?> ->
                Log.e(
                    "onSelected",
                    "onSelected: pathList=$pathList"
                )
            })
            .showSingleMediaType(true)
            .originalEnable(true)
            .maxOriginalSize(10)
            .autoHideToolbarOnSingleTap(true)
            .setOnCheckedListener(OnCheckedListener { isChecked: Boolean ->
                Log.e(
                    "isChecked",
                    "onCheck: isChecked=$isChecked"
                )
            })
            .forResult(REQUEST_CODE_CHOOSE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
//      mAdapter.setData(Matisse.obtainResult(data), Matisse.obtainPathResult(data))
            val result = Matisse.obtainResult(data)
            if (result != null && !result.isEmpty()) {
                updateImg(Matisse.obtainPathResult(data))
            }
        }
    }

    fun updateImg(path: List<String?>) {
        val file = File(path[0])
        Log.i("xx", "file")
        keyname = path[0]
        ImageUtil.instance.loadCircleImage(file, dataBinding.imgAvatar, 0, 0)
//        val requestFile =RequestBody.create("image/*".toMediaTypeOrNull(), file)
//        val part1 = MultipartBody.Part.createFormData("avatar", "xx.png", requestFile)
//        mPresenter.addPic(body);
        viewModel.picToken.value?.let { upload(it,file) }
    }


    private fun upload(uploadToken: String,file:File) {
        val startTime = System.currentTimeMillis()
        //配置断点续传
        /**
         * FileRecorder fileRecorder = null;
         * try {
         * fileRecorder = new FileRecorder("directory");
         * } catch (IOException e) {
         * e.printStackTrace();
         * }
         */
        //config配置上传参数
        var config: Configuration? = Configuration.Builder()
            .connectTimeout(90) // 链接超时。默认90秒
            .useHttps(true) // 是否使用https上传域名
//            .useConcurrentResumeUpload(true) // 使用并发上传，使用并发上传时，除最后一块大小不定外，其余每个块大小固定为4M，
//            .resumeUploadVersion(Configuration.RESUME_UPLOAD_VERSION_V2) // 使用新版分片上传
            .concurrentTaskCount(3) // 并发上传线程数量为3
            .responseTimeout(90) // 服务器响应超时。默认90秒
//            .zone(FixedZone.zone0) // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
            .build()
        GlobalConfiguration.getInstance().isDnsOpen = false
        val uploadManager = UploadManager(config)
        val opt = UploadOptions(null, null, true,
            { key, percent -> Log.i("qiniutest", "percent:$percent") }, null
        )
        keyname += "test_" + startTime;
        uploadManager.put(file, keyname, uploadToken,
            UpCompletionHandler { key, info, res -> //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                if (info.isOK) {
                    Log.i("qiniu", "Upload Success")
                    val fileKey = res.getString("key")
                    val fileHash = res.getString("hash")
                    val width = res.getString("width")
                    val height = res.getString("height")
                    Log.d("xyp","File Key: $fileKey")
                    Log.d("xyp","File Hash: $fileHash")
                    data1 = "ok"
                    MMKVUtil.encode(KVConst.PHOTO, fileKey, false)
                    viewModel.addAvatar(fileKey,width,height)
                } else {
                    Log.i("qiniu", "Upload Fail")
                    //如果失败，这里可以把 info 信息上报自己的服务器，便于后面分析上传错误原因
                }
                Log.i("qiniu", "$key,\r\n $info,\r\n $res")
            }, null
        )
    }

    private fun getPermission() {
        val PERMISSIONS = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
        PermissionUtil.getInstance().request(mActivity, PERMISSIONS,
            object : PermissionResultCallBack {
                override fun onPermissionGranted() {
                    viewModel.getuploadToken()
                }

                override fun onPermissionGranted(vararg p0: String?) {
                }

                override fun onPermissionDenied(vararg p0: String?) {
                    toSelfSetting(mActivity)
                    ToastUtils.show("需要打开存储权限")
                }

                override fun onRationalShow(vararg p0: String?) {
                    toSelfSetting(mActivity)
                    ToastUtils.show("需要打开存储权限")
                }

            })
    }

    fun toSelfSetting(context: Context) {
        val mIntent = Intent()
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
            mIntent.data = Uri.fromParts("package", context.packageName, null)
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.action = Intent.ACTION_VIEW
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails")
            mIntent.putExtra("com.android.settings.ApplicationPkgName", context.packageName)
        }
        context.startActivity(mIntent)
    }

}